import { Suspense, useEffect, useState } from 'react'
import { Routes, Route, useLocation, useNavigate, useSearchParams, useParams, Navigate } from 'react-router-dom'
import routes from './routes'
import { Mask, DotLoading, Toast } from 'antd-mobile'
import store from '../store'
import action from '../store/action'

/* 统一路由配置 */
const isCheckLogin = path => {
    let { base: { info } } = store.getState()
    let checkList = ['/personal', '/store', '/update'];
    return !info && checkList.includes(path);
}
const Element = (props) => {
    let { component: Component, meta, path } = props,
        // 获取路由信息，基于属性传递给组件
        location = useLocation(),
        navigate = useNavigate(),
        params = useParams(),
        [usp] = useSearchParams();
    let isShow = !isCheckLogin(path);
    let [_, setRandom] = useState(0);
    // 登录态校验
    useEffect(() => {
        if (isShow) return
        (async function () {
            let infoAction = await action.base.queryUserInfoAsync();
            let info = infoAction.info;
            if (!info) {
                // 如果获取后还是不存在，没有登录
                Toast.show({
                    icon: 'fail',
                    content: '请先登录'
                })
                navigate({
                    pathname: '/login',
                    search: `?to=${path}`
                }, { replace: true })
            }
            //如果获取到了信息，说明是登录的，我们派发任务把信息存储到容器中。
            store.dispatch(infoAction);
            setRandom(+new Date())
        })()
    })
    //修改 title
    let { title = '知乎日报-WebApp' } = meta || {}
    document.title = title
    return <>
        {isShow ? <Component location={location} navigate={navigate} params={params} usp={usp} /> : <Mask visible={true} opacity="thick">
            <DotLoading color='white' />
        </Mask>}
    </>
}

export default function RouteView() {
    return <Suspense fallback={<Mask visible={true} opacity="thick">
        <DotLoading color='white' />
    </Mask>} >
        <Routes>
            {routes.map(item => {
                let { name, path } = item
                return <Route key={name} path={path} element={<Element {...item} />} />
            })}
        </Routes>
    </Suspense>
}